<template>

	<view class="chatInterface" @contextmenu.prevent="">
	  <view class="scroll-view">
	    <image v-if="history.loading" class="history-loaded d-img-26" src="/static/im/pending.gif"/>
	    <view v-else :class="history.allLoaded ? 'history-loaded':'load'" @click="loadHistoryMessage(false)">
	      <view>{{ history.allLoaded ? '已经没有更多的历史消息' : '点击获取历史消息' }}</view>
	    </view>
		
	
	    <checkbox-group @change="selectMessages">
			
	      <!--消息记录-->
	      <view v-for="(message,index) in history.messages" :key="message.messageId">
			 
	        <!--时间显示，类似于微信，隔5分钟不发言，才显示时间-->
	        <view class="time-lag">
	          {{ renderMessageDate(message, index) }}
	        </view>
	        <view class="message-recalled" v-if="message.recalled">
	          <view v-if="message.recaller.id === faxinuid" class="message-recalled-self">
	            <view>你撤回了一条消息</view>
	            <span v-if="message.type === 'text' && Date.now()-message.timestamp< 60 * 1000 "
	                  @click="editRecalledMessage(message.payload.text)">重新编辑</span>
	          </view>
	          <view v-else>{{ message.recaller.data.name }}撤回了一条消息</view>
	        </view>
	        <view class="message-item" v-else>
	          <view class="message-item-checkbox">
	            <checkbox v-show="messageSelector.visible && message.status !== 'sending'" :value="message.messageId"
	                      :checked="messageSelector.messages.includes(message)"/>
	          </view>

			    <view class="message-item-content" :class="{'self' : message.senderId ===  faxinuid}">
					<view class="avatar d-yuanjiao-50">
					  <image class="d-yuanjiao-50" :src="message.senderId === faxinuid ? faxingerenxinxi.avatar : gerenxinxi.avatar"></image>
					</view>
					<view class="content" @click.right="showActionPopup(message)" @longpress="showActionPopup(message)">
						<view class="message-payload">
							<b class="pending" v-if="message.status === 'sending'"></b>
							<b class="send-fail" v-if="message.status === 'fail'"></b>
							<!--文本-->
							<view  class="text-content d-yuanjiao-10" v-if="message.type === 'text'" v-html="renderTextMessage(message)"></view>
							<!--图片-->
							<image v-if="message.type === 'image'"
							   :data-url="message.payload.url"
							   :src="message.payload.thumbnail"
							   class="image-content"
							   @click="showImageFullScreen"
							></image>
							<!--视频-->
							<view class="video-snapshot" v-if="message.type === 'video'" :data-url="message.payload.video.url"
							      @click="playVideo">
							  <image
							    :src="message.payload.thumbnail.url"
							    :style="{height: getImageHeight(message.payload.thumbnail.width,message.payload.thumbnail.height)+'rpx' }"
							    mode="heightFix"
							  ></image>
							  <view class="video-play-icon"></view>
							</view>
						</view>
					</view>
			    </view>
	          <!--view class="message-item-content" :class="{'self' : message.senderId ===  currentUser.id}">
	            
	
	            <view class="content" @click.right="showActionPopup(message)" @longpress="showActionPopup(message)">
	              <view class="message-payload">
	                <b class="pending" v-if="message.status === 'sending'"></b>
	                <b class="send-fail" v-if="message.status === 'fail'"></b>
	                <view v-if="message.type === 'text'" v-html="renderTextMessage(message)"></view>
	                <image v-if="message.type === 'image'"
	                   :data-url="message.payload.url"
	                   :src="message.payload.thumbnail"
	                   class="image-content"
	                   @click="showImageFullScreen"
	                ></image>
	                <view class="video-snapshot" v-if="message.type === 'video'" :data-url="message.payload.video.url"
	                      @click="playVideo">
	                  <image
	                    :src="message.payload.thumbnail.url"
	                    :style="{height: getImageHeight(message.payload.thumbnail.width,message.payload.thumbnail.height)+'rpx' }"
	                    mode="heightFix"
	                  ></image>
	                  <view class="video-play-icon"></view>
	                </view>
	                <view class="file-content" v-if="message.type === 'file'">
	                  <view class="file-info">
	                    <span class="file-name">{{ message.payload.name }}</span>
	                    <span class="file-size">{{ (message.payload.size / 1024).toFixed(2) }}KB</span>
	                  </view>
	                  <image class="file-img" src="/static/im/file-icon.png"></image>
	                </view>
	                <view v-if="message.type ==='audio'" class="audio-content" @click="playAudio(message)">
	                  <view class="audio-facade" :style="{width:Math.ceil(message.payload.duration)*7 + 50 + 'px'}">
	                    <view
	                      class="audio-facade-bg"
	                      :class="{'play-icon':audioPlayer.playingMessage && audioPlayer.playingMessage.messageId === message.messageId}"
	                    ></view>
	                    <view>{{Math.ceil(message.payload.duration) || 1}}<span>"</span></view>
	                  </view>
	                </view>
	                <view v-if="message.type === 'order'" class="order-content">
	                  <view class="order-id">订单号：{{ message.payload.id }}</view>
	                  <view class="order-body">
	                    <image :src="message.payload.url" class="order-img"></image>
	                    <view>
	                      <view class="order-name">{{ message.payload.name }}</view>
	                      <view class="order-info">
	                        <view class="order-price">{{ message.payload.price }}</view>
	                        <view class="order-count">共{{ message.payload.count }}件</view>
	                      </view>
	                    </view>
	                  </view>
	                </view>
	              </view>
	              <view v-if="message.senderId === currentUser.id" :class="message.read ?'message-read':'message-unread'">
	                <view v-if="message.status === 'success'">{{ message.read ? '已读' : '未读' }}</view>
	              </view>
	            </view>
	          </view-->
	        </view>
	      </view>
	    </checkbox-group>
	  </view>
	  <view class="action-box" v-if="!videoPlayer.visible && !messageSelector.visible">
	    <view class="action-top">
			<!-- #ifdef APP-PLUS -->
	      <view @click="switchAudioKeyboard">
	        <image class="more" v-if="audio.visible" src="/static/im/jianpan.png"></image>
	        <image class="more" v-else src="/static/im/audio.png"></image>
	      </view>
		  <!-- #endif -->
	      <view v-if="audio.visible" class="record-input" @click="onRecordStart" @touchend.stop="onRecordEnd" @touchstart.stop="onRecordStart">
	        {{ audio.recording ? '松开发送' : '按住录音' }}
	      </view>
		  
	      <!-- GoEasyIM最大支持3k的文本消息，如需发送长文本，需调整输入框maxlength值 -->
	      <input v-else v-model="text" @confirm="sendTextMessage" class="consult-input" maxlength="700" placeholder="发送消息" type="text" />
	      
		  <view @click="switchEmojiKeyboard">
	        <image class="more" v-if="emoji.visible" src="/static/im/jianpan.png"></image>
	        <image class="more" v-else src="/static/im/emoji.png"></image>
	      </view>
	      <view>
	        <image @click="showOtherTypesMessagePanel()" class="more" src="/static/im/more.png"/>
	      </view>
	      <view v-if="text" class="send-btn-box">
	        <text class="btn" @click="sendTextMessage()">发送</text>
	      </view>
	    </view>
	    <!--展示表情列表-->
	    <view class="action-bottom action-bottom-emoji" v-if="emoji.visible">
	      <image class="d-img-35" v-for="(emojiItem, emojiKey, index) in emoji.map" :key="index"
	             :src="emoji.url + emojiItem" @click="chooseEmoji(emojiKey)"></image>
	    </view>
	    <!--其他类型消息面板-->
	    <view v-if="otherTypesMessagePanelVisible" class="action-bottom">
	      <view class="more-icon">
	        <image @click="sendImageMessage()" class="operation-icon" src="/static/im/picture.png"></image>
	        <view class="operation-title">图片</view>
	      </view>
	      <!--view class="more-icon">
	        <image @click="sendVideoMessage()" class="operation-icon" src="/static/im/video.png"></image>
	        <view class="operation-title">视频</view>
	      </view>
	      <view class="more-icon">
	        <image @click="showOrderMessageList()" class="operation-icon" src="/static/im/order.png"></image>
	        <view class="operation-title">订单</view>
	      </view-->
	    </view>
	  </view>
	  <view class="action-popup" @touchmove.stop.prevent v-if="actionPopup.visible">
	    <view class="layer"></view>
	    <view class="action-list">
	      <view class="action-item" @click="deleteSingleMessage">删除</view>
	      <view class="action-item" v-if="actionPopup.recallable" @click="recallMessage">撤回</view>
	      <view class="action-item" @click="showCheckBox">多选</view>
	      <view class="action-item" @click="hideActionPopup">取消</view>
	    </view>
	  </view>
	  <view class="messageSelector-box" v-if="messageSelector.visible">
	    <image class="messageSelector-btn" @click="deleteMultipleMessages" src="/static/im/delete.png"></image>
	  </view>
	  <view class="record-loading" v-if="audio.recording"></view>
	  <video v-if="videoPlayer.visible" :src="videoPlayer.url" id="videoPlayer"
	         @fullscreenchange="onVideoFullScreenChange"></video>
	  <view v-if="orderList.visible" class="order-list">
	    <view class="orders-content">
	      <view class="title">
	        <view>请选择一个订单</view>
	        <view class="close" @click="hideOrderMessageList">×</view>
	      </view>
	      <view class="orders">
	        <view
	          v-for="(order, index) in orderList.orders"
	          :key="index" class="order-item"
	          @click="sendOrderMessage(order)"
	        >
	          <view class="order-id">订单号：{{ order.id }}</view>
	          <view class="order-body">
	            <image :src="order.url" class="order-img"></image>
	            <view class="order-name">{{ order.name }}</view>
	            <view class="order-right">
	              <view class="order-price">{{ order.price }}</view>
	              <view class="order-count">共{{ order.count }}件</view>
	            </view>
	          </view>
	        </view>
	      </view>
	    </view>
	  </view>
	</view>

</template>

<script>
import toubu from "@/components/toubu/toubu";  //引入头部组件
import EmojiDecoder from '../../utils/EmojiDecoder';
import config from "../../utils/config";
import {formatDate} from '../../utils/utilsim';
var Api = require("../../utils/api.js");
var util = require("../../utils/util.js");

var wxApi = require("../../utils/wxApi.js");
var wxRequest = require("../../utils/wxRequest.js");
var webSiteName = config.getWebsiteName;
var domain = config.getDomain;

export default {
	name: 'duanxin',
	
  data() {
	  const emojiUrl = config.getDomain+'/static/assets/comment/emotions/';
	  const emojiMap = {
		  '[傲慢]': 'aoman.gif',
		  '[白眼]': 'baiyan.gif',
		  '[鄙视]': 'bishi.gif',
		  '[呲牙]': 'ciya.gif',
		  '[得以]': 'deyi.gif',
		  '[得以]': 'deyi.gif',
		  '[得以]': 'deyi.gif',
		  '[得以]': 'deyi.gif',
		  '[得以]': 'deyi.gif',
		  '[得以]': 'deyi.gif',
		  '[得以]': 'deyi.gif',
		  '[得以]': 'deyi.gif',
		  '[得以]': 'deyi.gif',
	  };
    return {
		//聊天文本框
		text: '',
		friend: null,
		to: {},// 作为createMessage的参数
		currentUser: null,
      
      categoriesList: {},
      floatDisplay: "none",
      // userInfo: [],
      webSiteName: webSiteName,
      domain: domain,
	  www: [],
	  guid:'',
	  gerenxinxi: [],
	  history: {
	    messages: [],
	    allLoaded: false,
	    loading: false
	  },
	  lishi:{
		  messages:[]
	  },
	  videoPlayer: {
	    visible: false,
	    url: '',
	    context: null
	  },
	  // 消息选择
	  messageSelector: {
	    visible: false,
	    messages: []
	  },
	  to: {},
	  audio: {
	    startTime: null,
	    //语音录音中
	    recording: false,
	    //录音按钮展示
	    visible: false
	  },
	  //定义表情列表
	  emoji: {
	    url: emojiUrl,
	    map: emojiMap,
	    visible: false,
	    decoder: new EmojiDecoder(emojiUrl, emojiMap),
	  },
	  //是否展示‘其他消息类型面板’
	  otherTypesMessagePanelVisible: false,
	  orderList: {
	    orders: [],
	    visible: false
	  },
	  // 展示消息删除弹出框
	  actionPopup: {
	    visible: false,
	    message: null,
	    recallable: false,
	  },
	  shouxinuid:'', //收信人
	  faxinuid:'' ,//发信人
	  faxingerenxinxi:[]
	  
    };
  },

  components: {
	  toubu,
  },
  props: {},
  onLoad: function (options) {
	var duixin = this;
	duixin.getWww();
	
	uni.setNavigationBarTitle({
	  title: '消息'
	});
	
	
	duixin.guid = options.uid;
	duixin.faxinuid = options.faxinuid;
	duixin.shouxinuid = options.uid;
	
	console.log("duixin.faxinuid",duixin.faxinuid);
	var userInfo = uni.getStorageSync('userInfo');
	//self.userInfo = userInfo;
	//console.log("userInfo1",userInfo);
	if (userInfo) {
		var member = uni.getStorageSync('member');
		var uid = uni.getStorageSync('memberuid');
		
	} else {
		//否则跳转到登录页面
		uni.reLaunch({ url: '/pages/login/login'}) // 跳转到首页
	}
	
	duixin.getFaxinGerenxinxi();
	duixin.getGerenxinxi();
	duixin.initialGoEasyListeners();
	//console.log("duixin.",duixin.faxingerenxinxi);
	//聊天对象
	/*let id = options.uid;
	let faxinuid = duixin.faxinuid;
	this.currentUser = getApp().globalData.currentUser;
	this.to = {
	  id: faxinuid,
	  type: 'private',
	  data: {
	    name: this.friend.name,
	    avatar: this.friend.avatar
	  }
	};*/
	
	
	//console.log("gerenxinxi.",duixin.gerenxinxi) //连接成功
  },
  onShow: function () {
	  var duixin = this;
	  console.log("duixin.GoEasy",duixin.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED);
	  duixin.goEasy.im.on(duixin.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, duixin.renderConversations); //监听会话列表变化
	  duixin.loadConversations(); //加载会话列表
  },
  onReady() {
    this.loadHistoryMessage(true);
    //this.videoPlayer.context = uni.createVideoContext('videoPlayer', this);
    // https://uniapp.dcloud.io/api/ui/navigationbar?id=setnavigationbartitle
    //uni.setNavigationBarTitle({ title: this.friend.name });
  },
  onPullDownRefresh(e) {
    this.loadHistoryMessage(false);
  },
  onShareAppMessage: function () {
    return {
      title: '分享“' + config.getWebsiteName + '”消息.',
      path: 'pages/quan/wode',
      success: function (res) {// 转发成功
      },
      fail: function (res) {// 转发失败
      }
    };
  },
  onUnload() {
	  var duixin = this;
    //退出聊天页面之前，清空监听器
    duixin.goEasy.im.off(duixin.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, duixin.onMessageReceived);
    duixin.goEasy.im.off(duixin.GoEasy.IM_EVENT.MESSAGE_DELETED, duixin.onMessageDeleted);
  },
  methods: {

	//渲染文本消息，如果包含表情，替换为图片
	//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
	renderTextMessage(message) {
	  return '<span class="text-content">' + this.emoji.decoder.decode(message.payload.text) + '</span>'
	},
	//像微信那样显示时间，如果有几分钟没发消息了，才显示时间
	//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
	renderMessageDate(message, index) {
		var duixin = this;
		//console.log('message',message); 
	  if (index === 0) {
	    return formatDate(message['timestamp'])
	  } else {
	    if (message['timestamp'] - duixin.history.messages[index -1]['timestamp'] > 5 * 60 * 1000) {
	      return formatDate(message['timestamp'])
	    }
	  }
	  return '';
	},
	//获取站点
	getWww() {
	  	var self = this;
	  	self.setData({
	  	  www: []
	  	});
	  	var getTubiaoRequest = wxRequest.getRequest(Api.getWwwUrl());
	  	getTubiaoRequest.then(response => {
	  		if (response.data.code == 1) {
	  		  //console.log(response.data.data); 
	  		  self.www = response.data.data
	  		} else {
	  		  self.setData({
	  			displaySwiper: "none"
	  		  });
	  		}
	  	});
	},

	// 点击
	quanzi(tieid) {
		console.log('点击',tieid); 
		var url = '../quan/quanzi?&id='+tieid;
		uni.navigateTo({
			url: url
		});
	},
	//建立mi用户链接
	getUidlianjie(data) {
		var duixin = this;
		var uid = duixin.faxinuid;
		var faxinuiddata = data;
		console.log("连接成功faxinuiddata",faxinuiddata) //连接成功
		duixin.goEasy.connect({
			id: faxinuiddata.id, //im必填，最大长度60字符
			data: {
			  name: faxinuiddata.name,
			  avatar: faxinuiddata.avatar
			},
			onSuccess: function () { //连接成功
			console.log("连接成功111") //连接成功
			},
			onFailed: function (error) { //连接失败
			console.log("Failed to connect GoEasy, code:"+error.code+ ",error:"+error.content);
			},
			onProgress: (attempts) => {
			console.log('GoEasy is connecting', attempts);
			}
		});
	},
	initialGoEasyListeners() {
	  // 监听私聊消息
	  this.goEasy.im.on(this.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, this.onMessageReceived);
	  //监听消息删除
	  this.goEasy.im.on(this.GoEasy.IM_EVENT.MESSAGE_DELETED, this.onMessageDeleted);
	},
	onMessageReceived (message) {
		var duixin = this;
		var faxinuid = duixin.faxinuid;
		var shouxinuid = duixin.shouxinuid;
	  let senderId = message.senderId;
	  let receiverId = message.receiverId;
	  let friendId = faxinuid === senderId ? receiverId : senderId;
	  if (friendId === shouxinuid) {
	    this.history.messages.push(message);
	    //聊天时，收到消息标记为已读
	    this.markPrivateMessageAsRead();
	    //收到新消息，是滚动到最底部
	    this.scrollToBottom();
	  }
	},
	onMessageDeleted (deletedMessages) {
		var duixin = this;
		var faxinuid = duixin.faxinuid;
		var shouxinuid = duixin.shouxinuid;
	  deletedMessages.forEach(message => {
	    let senderId = message.senderId;
	    let receiverId = message.receiverId;
	    let friendId = faxinuid === senderId ? receiverId : senderId;
	    if (friendId === shouxinuid) {
	      let index = this.history.messages.indexOf(message);
	      if (index > -1) {
	        this.history.messages.splice(index, 1);
	      }
	    }
	  });
	},
	//收信个人信息
	getGerenxinxi() {
		var duixin = this;
		duixin.setData({
		  gerenxinxi: []
		});
		var uid = duixin.shouxinuid;
		var getYonghuXinxiRequest = wxRequest.getRequest(Api.getYonghuXinxi(uid));
		getYonghuXinxiRequest.then(response => {
			if (response.data.code == 1) {
			  //console.log("111",response.data.data); 
			  duixin.gerenxinxi = response.data.data
			  //duixin.getUidlianjie(duixin.gerenxinxi);
			} else {
			  duixin.setData({
				displaySwiper: "none"
			  });
			}
		});
	},
	//发信个人信息
	getFaxinGerenxinxi() {
		var duixin = this;
		
		var uid = duixin.faxinuid;
		var getYonghuXinxiRequest = wxRequest.getRequest(Api.getYonghuXinxi(uid));
		getYonghuXinxiRequest.then(response => {
			if (response.data.code == 1) {
			  //console.log("111",response.data.data); 
			  duixin.faxingerenxinxi = response.data.data
			  duixin.getUidlianjie(duixin.faxingerenxinxi);

			  //duixin.getUidlianjie(duixin.faxingerenxinxi);
			  console.log("faxingerenxinxi",duixin.faxingerenxinxi); 
			} else {
			  duixin.setData({
				//displaySwiper: "none"
			  });
			}
		});
	},
	//发文字
	sendTextMessage() {
		
		var duixin = this;
		var faxinuid = duixin.faxinuid;
		var shouxinuid = duixin.shouxinuid;
		var faxinuiddata = duixin.faxingerenxinxi;
		var gerenxinxidata = duixin.gerenxinxi;
	  if (this.text.trim() !== '') {
	    let body = this.text;
	    if (this.text.length >= 50) {
	      body = this.text.substring(0, 30) + '...';
	    }
		//console.log("faxinuid",faxinuid); 
		console.log("duixin.faxingerenxinxi000000",duixin.faxingerenxinxi); 
		
	    this.goEasy.im.createTextMessage({
			senderId: faxinuid,
			senderData: {"avatar": faxinuiddata.avatar, "nickname": faxinuiddata.name},
			text: this.text,
			to: {
			type: 'private',   //私聊还是群聊this.goEasy.IM_SCENE.PRIVATE，群聊为GoEasy.IM_SCENE.GROUP
			id: shouxinuid, //接收方用户id
			data: {"avatar": gerenxinxidata.avatar, "nickname": gerenxinxidata.name} //接收方用户扩展数据, 任意格式的字符串或者对象，用于更新会话列表conversation.data
			},
			notification: {
			title: this.text + '发来一段文字',
			body: body,
			sound: 'message',
			badge: '+1'
			},
			onSuccess: (message) => {
				console.log('发送成功', message);
			    duixin.sendMessage(message);
				//duixin.history.messages.push(message);
				
			},
			onFailed: (e) => {
			console.log('error11 :', e);
			}
	    });
	  }
	  this.text = '';
	},
	sendMessage(message) {
		var duixin = this;
	  duixin.history.messages.push(message);
	  duixin.scrollToBottom();
	  duixin.goEasy.im.sendMessage({
	    message: message,
	    onSuccess: function (message) {
	      console.log('发送成功.', message);
	    },
	    onFailed: function (error) {
	      if (error.code === 507) {
	        console.log('发送语音/图片/视频/文件失败，没有配置OSS存储，详情参考：https://docs.goeasy.io/2.x/im/message/media/alioss');
	      } else {
	        console.log('发送失败:', error);
	      }
	    }
	  });
	},
	scrollToBottom() {
	  this.$nextTick(() => {
	    uni.pageScrollTo({
	      scrollTop: 2000000,
	      duration: 0
	    });
	  });
	},
	// 图片
	sendImageMessage() {
		var duixin = this;
		var shouxindata = duixin.gerenxinxi;
		duixin.to = {
		  id: shouxindata.id,
		  type: 'private',
		  data: {
		    name: shouxindata.name,
		    avatar: shouxindata.avatar
		  }
		};
		//console.log('图片shouxindata', shouxindata);
	  uni.chooseImage({
	    count: 9,
	    success: (res) => {
	      res.tempFiles.forEach(file => {
	        this.goEasy.im.createImageMessage({
	          to: duixin.to,
	          file: file,
	          notification: {
	            title: shouxindata.name + '发来一张图片',
	            body: '[图片消息]',		// 字段最长 50 字符
	            sound: 'message',
	            badge: '+1'
	          },
	          beforeSend:()=>{
	
	          },
	          customizedUpload:(file,message)=> {
	            return new Promise((resolve, reject) => {
	              //上传图片到自己的服务器
	              uni.uploadFile({
	                url: 'https://www.goeasy.io/2.0/im/upload', //仅为示例，非真实的接口地址
	                filePath: file.path,
	                name: 'file',
	                success: (uploadFileRes) => {
	                  let data = JSON.parse(uploadFileRes.data);
	                  if (data.code === 0) {
	                    message.url = data.data.url;
	
	                    resolve();
	                  } else {
	                    reject();
	                  }
	                },
	                fail: (e) => {
	                  reject(e);
	                }
	              });
	            })
	          },
	          onProgress: function (progress) {
	            console.log(progress)
	          },
	          onSuccess: (message) => {
	            this.otherTypesMessagePanelVisible = false;
	            this.sendMessage(message);
	          },
	          onFailed: (e) => {
	            console.log('error :', e);
	          }
	        });
	      })
	    }
	  });
	},
	//视频
	sendVideoMessage() {
		var duixin = this;
		var shouxindata = duixin.gerenxinxi;
		duixin.to = {
		  id: shouxindata.id,
		  type: 'private',
		  data: {
		    name: shouxindata.name,
		    avatar: shouxindata.avatar
		  }
		};
	  uni.chooseVideo({
	    success: (res) => {
	      this.goEasy.im.createVideoMessage({
	        to: this.to,
	        file: res,
	        notification: {
	          title: shouxindata.name + '发来一个视频',
	          body: '[视频消息]',		// 字段最长 50 字符
	          sound: 'message',
	          badge: '+1'
	        },
	        onProgress: function (progress) {
	          console.log(progress)
	        },
	        onSuccess: (message) => {
	          this.otherTypesMessagePanelVisible = false;
	          this.sendMessage(message);
	        },
	        onFailed: (e) => {
	          console.log('error :', e);
	        }
	      });
	    }
	  })
	},
	loadHistoryMessage(scrollToBottom) {//历史消息
		var duixin = this;
	  duixin.history.loading = true;
	  var faxinuid = duixin.faxinuid;
	  var shouxinuid = duixin.shouxinuid;
	  let lastMessageTimeStamp = null;
	  let lastMessage = duixin.history.messages[0];
	  if (lastMessage) {
	    lastMessageTimeStamp = lastMessage.timestamp;
	  }
	  //console.log('lastMessage.timestamp0000:', lastMessage);
	  duixin.goEasy.im.history({
		id: shouxinuid,
		type: 'private',
	    lastTimestamp: lastMessageTimeStamp,
	    limit: 10,
	    onSuccess: (result) => {
			//console.log('获取历史成功:', result);
	      uni.stopPullDownRefresh();
	      this.history.loading = false;
	      let messages = result.content;
	      if (messages.length === 0) {
	        this.history.allLoaded = true;
	      } else {
	        if (lastMessageTimeStamp) {
	          this.history.messages = messages.concat(this.history.messages);
	        } else {
	          this.history.messages = messages;
	        }
	        if (messages.length < 10) {
	          this.history.allLoaded = true;
	        }
	        if (scrollToBottom) {
	          this.scrollToBottom();
	          //收到的消息设置为已读
	          this.markPrivateMessageAsRead();
	        }
	      }
	    },
	    onFailed: (error) => {
	      //获取失败
	      console.log('获取历史消息失败0000:', error);
	      uni.stopPullDownRefresh();
	      this.history.loading = false;
	    }
	  });
	},
	//表情
	switchEmojiKeyboard() {
	  this.emoji.visible = !this.emoji.visible;
	  this.otherTypesMessagePanelVisible = false;
	},
	chooseEmoji(emojiKey) {
	  this.text += emojiKey;
	},
	//附加
	showOtherTypesMessagePanel() {
	  this.otherTypesMessagePanelVisible = !this.otherTypesMessagePanelVisible;
	  this.emoji.visible = false;
	},
	//撤回
	showActionPopup(message) {
	  const MAX_RECALLABLE_TIME = 3 * 60 * 1000; //3分钟以内的消息才可以撤回
	  this.messageSelector.messages = [message];
	  if ((Date.now() - message.timestamp) < MAX_RECALLABLE_TIME && message.senderId === this.faxinuid && message.status === 'success') {
	    this.actionPopup.recallable = true;
	  } else {
	    this.actionPopup.recallable = false;
	  }
	  this.actionPopup.visible = true;
	},
	markPrivateMessageAsRead() {
	  this.goEasy.im.markMessageAsRead({
	    id: this.shouxinuid,
	    type: 'private',
	    onSuccess: function () {
	      console.log('标记私聊已读成功');
	    },
	    onFailed: function (error) {
	      console.log("标记私聊已读失败", error);
	    }
	  });
	},
	showImageFullScreen(e) {
	  let imagesUrl = [e.currentTarget.dataset.url];
	  uni.previewImage({
	    urls: imagesUrl
	  });
	},
	//语音录制按钮和键盘输入的切换
	switchAudioKeyboard() {
	  this.audio.visible = !this.audio.visible;
	  if (uni.authorize) {
	    uni.authorize({
	      scope: 'scope.record',
	      fail: () => {
	        uni.showModal({
	          title: '获取录音权限失败',
	          content: '请先授权才能发送语音消息！'
	        });
	      }
	    });
	  }
	},
	onRecordStart() {
	  try {
	    // 更多配置参考uniapp：https://uniapp.dcloud.net.cn/api/media/record-manager.html#getrecordermanager
	    recorderManager.start({
	      duration: 600000 // 指定录音的时长,单位 ms
	    });
	  } catch (e) {
	    uni.showModal({
	      title: '录音错误',
	      content: '请在app和小程序端体验录音，Uni官方明确H5不支持getRecorderManager, 详情查看Uni官方文档'
	    });
	  }
	},
	onRecordEnd() {
	  try {
	    recorderManager.stop();
	  } catch (e) {
	    console.log(e);
	  }
	},
	// 加载最新的会话列表
	loadConversations() {
		var duixin = this;
		//console.log('会话11111');
		duixin.goEasy.im.latestConversations({
		  onSuccess: (result) => {
			//console.log('会话00000',result);
		    uni.hideLoading();
		    let content = result.content;
		    duixin.renderConversations(content);
		    let unreadTotal = content.unreadTotal;
		    if(unreadTotal > 0) {
		      uni.setTabBarBadge({
		        index: 0,
		        text: unreadTotal.toString()
		      });
		    }else{
		      uni.removeTabBarBadge({index: 0});
		    }
		  },
		  onFailed: (error) => {
		    uni.hideLoading();
		    console.log('获取最新会话列表失败, error:', error);
		  }
		});
	  
	},
	renderConversations(content) {
		var duixin = this;
	  duixin.conversations = content.conversations;
	},
	deleteSingleMessage() {
	  uni.showModal({
	    content: '确认删除？',
	    success: (res) => {
	      this.actionPopup.visible = false;
	      if (res.confirm) {
	        this.deleteMessage();
	      }
	    },
	  })
	},
	showCheckBox() {
	  this.messageSelector.messages = [];
	  this.messageSelector.visible = true;
	  this.actionPopup.visible = false;
	},
	hideActionPopup () {
	  this.actionPopup.visible = false;
	  this.actionPopup.message = null;
	},
	deleteMultipleMessages() {
	  if (this.messageSelector.messages.length > 0) {
	    uni.showModal({
	      content: '确认删除？',
	      success: (res) => {
	        this.messageSelector.visible = false;
	        if (res.confirm) {
	          this.deleteMessage();
	        }
	      },
	    })
	  }
	},
	selectMessages(e) {
	  const selectedMessageIds = e.detail.value;
	  let selectedMessages = [];
	  this.history.messages.forEach(message => {
	    if (selectedMessageIds.includes(message.messageId)) {
	      selectedMessages.push(message);
	    }
	  })
	  this.messageSelector.messages = selectedMessages;
	},
	deleteMessage() {
	  this.goEasy.im.deleteMessage({
	    messages: this.messageSelector.messages,
	    onSuccess: (result) => {
	      this.messageSelector.messages.forEach(message => {
	        let index = this.history.messages.indexOf(message);
	        if (index > -1) {
	          this.history.messages.splice(index, 1);
	        }
	      });
	      this.messageSelector.messages = [];
	    },
	    onFailed: (error) => {
	      console.log('error:', error);
	    }
	  });
	},
	recallMessage() {
	  this.actionPopup.visible = false;
	  this.goEasy.im.recallMessage({
	    messages: this.messageSelector.messages,
	    onSuccess: () => {
	      console.log('撤回成功');
	    },
	    onFailed: (error) => {
	      console.log('撤回失败,error:', error);
	    }
	  });
	},
  }
};
</script>
<style>
@import "./chatInterface.css";
.text-content {
    padding: 16rpx;
    border-radius: 12rpx;
    color: #000000;
    background: #FFFFFF;
    word-break: break-all;
    text-align: left;
    vertical-align: center;
    display: block;
}
.action-bottom image {
    width: 70rpx;
    height: 70rpx;
}
</style>